﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.Mvc;

using AVCare.LMS.Web.Models;
using AVCare.LMS.Models;
using AVCare.LMS.DataAccess;
using AVCare.LMS.IO;

using AVCare.LMS.Util;

namespace AVCare.LMS.Web.Controllers
{
    public class DiskController : Controller
    {
        // GET: /Disk/
        public ActionResult Index(string id)
        {
            FileListModel model = new FileListModel();
            IFileHelper helper = HelperProvider.GetFileHelper();
            Guid rootID = helper.GetRoot(User.Identity.Name);
            Guid fid;
            if (id == null || id == null)
            {
                fid = rootID;
            }
            else
            {
                fid = new Guid(id);
            }

            model.Folders = helper.GetFolders(fid);
            model.Files = helper.GetFiles(fid);
            model.RootID = rootID;
            model.ParentID = helper.GetParent(fid);
            model.CurrentFolder = helper.GetFolder(fid);
            model.ShowShare = fid == rootID;
            return View("Index", model);
        }

        public ActionResult Sharedfolder(string id)
        {
            SharedFileModel model = new SharedFileModel();
            IFileHelper helper = HelperProvider.GetFileHelper();

            if (id == null || id == null)
            {
                model.Files = new List<LMS.Models.File>();
                List<Folder> folders = helper.GetShareFolder();
                ShareFolder sf;
                List<ShareFolder> list = new List<ShareFolder>();
                foreach (var item in folders)
                {
                    sf = new ShareFolder();
                    sf.folder = item;
                    sf.ShareRole = helper.GetShareFolder(item.ID).Role;
                    list.Add(sf);

                }
                model.Folders = list;
            }
            else
            {
                Guid fid = new Guid(id);
                List<Folder> folders = helper.GetFolders(fid);
                ShareFolder sf;
                List<ShareFolder> list = new List<ShareFolder>();
                foreach (var item in folders)
                {
                    sf = new ShareFolder();
                    sf.folder = item;
                    sf.ShareRole = 1;
                    list.Add(sf);

                }
                model.Folders = list;
                model.Files = helper.GetFiles(fid);
                model.ParentID = helper.GetParent(fid);
                
            }
            
            return View("SharedFolder", model);
        }


        public ActionResult Downdoad(string id)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            LMS.Models.File file = helper.GetFile(new Guid(id));
            string fileName = file.FileName;
            string userpath = FileOption.GetUserPath(User.Identity.Name);
            string folderpath = helper.GetFolder(file.FolderID).Path;

            byte[] fileData = FileOption.GetFile(Path.Combine(userpath, folderpath, fileName));

            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlEncode(fileName).Replace("+", " ")));
            return File(fileData, "application/octet-stream");
        }

        public ActionResult Upload(FormCollection form)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();

            LMS.Models.File f = new LMS.Models.File();

            f.CreateTime = DateTime.Now;
            f.FileName = form["filename"].Substring(form["filename"].LastIndexOf(@"\") == -1 ? 0 : form["filename"].LastIndexOf(@"\") + 1);
            string folderString = form["filename"].Substring(0, form["filename"].LastIndexOf(@"\") == -1 ? 0 : form["filename"].LastIndexOf(@"\"));
            f.FolderID = helper.GetFolder(new Guid(form["currentid"]), folderString, User.Identity.Name).ID;
            f.ID = Guid.NewGuid();
            f.LastEditTime = DateTime.Now;
            f.UserID = User.Identity.Name;

            string filename = Path.Combine(HttpUtility.UrlDecode(form["currentPath"]), form["filename"]);

            f.MD5 = FileOption.GetFileMD5(filename);
            f.Size = FileOption.GetFileSize(filename);
            f.Received = false;


            helper.SaveFile(f);

            return new EmptyResult();
        }

        public ActionResult RenameFolder(FormCollection form)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            helper.ReNameFolder(new Guid(form["id"]), form["newName"]);

            return new EmptyResult();
        }

        public ActionResult RenameFile(FormCollection form)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            string newName = form["newName"];
            Guid id = new Guid(form["id"]);
            LMS.Models.File file = helper.GetFile(id);
            string oldName = file.FileName;


            helper.ReNameFile(id, newName);

            string userpath = FileOption.GetUserPath(User.Identity.Name);
            string folderpath = helper.GetFolder(file.FolderID).Path;

            System.IO.File.Move(Path.Combine(userpath, folderpath, oldName), Path.Combine(userpath, folderpath, newName));

            return new EmptyResult();
        }

        public ActionResult NewFolder(FormCollection form)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            Folder newFolder = helper.CreateFolder(new Guid(form["parentid"]), form["foldername"], User.Identity.Name);
            string path = FileOption.GetUserPath(User.Identity.Name);
            path = Path.Combine(path, newFolder.Path);
            FileOption.CreateFolder(path);

            return Content(newFolder.ID.ToString());
        }

        public ActionResult DeleteFolder(Guid id)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            if (!SystemConfigurationManager.BackupUserFile)
            {
                Folder folder = helper.GetFolder(id);
                string path = FileOption.GetUserPath(User.Identity.Name);
                FileOption.DeleteFolder(Path.Combine(path, folder.Path));
            }
            helper.DeleteFolder(id);
            return new EmptyResult();
        }

        public ActionResult DeleteFile(Guid id)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            if (!SystemConfigurationManager.BackupUserFile)
            {
                AVCare.LMS.Models.File file = helper.GetFile(id);
                string fileName = file.FileName;
                string userpath = FileOption.GetUserPath(User.Identity.Name);
                string folderpath = helper.GetFolder(file.FolderID).Path;

                FileOption.DeleteFile(Path.Combine(userpath, folderpath, fileName));
            }
            helper.DeleteFile(id);
            return new EmptyResult();
        }

        public ActionResult FileInfo(string id)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            AVCare.LMS.Models.File file = helper.GetFile(new Guid(id));

            return Json(new { type = "file", id = file.ID, name = file.FileName, user = file.UserID, md5 = file.MD5, lastEditTime = file.LastEditTime.ToLongDateString(), size = file.Size });
        }

        public ActionResult FolderInfo(string id)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            AVCare.LMS.Models.Folder folder = helper.GetFolder(new Guid(id));

            return Json(new { type = "folder", id = folder.ID, name = folder.Name, user = folder.UserID });
        }

        public ActionResult ShareType(string id)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            SharedFolder folder = helper.GetShareFolder(new Guid(id));
            if (folder == null)
            {
                return Json("0");
            }
            return Json((int)folder.Role);
        }
        public ActionResult ShareFolder(FormCollection form)
        {
            IFileHelper helper = HelperProvider.GetFileHelper();
            helper.ShareFolder(new Guid(form["id"]), form["password"], (ShareRole)Convert.ToInt32(form["role"]));


            return new EmptyResult();
        }
    }
}
